export function createStore(reducer,fn){
  let state;// stat就是用用来存储公用数据的
  let listeners = [];// 用来存储 subscribe 传进来的事件
  let getState = function(){
    // 这个函数只是用来返回 state的
    return state&&JSON.parse(JSON.stringify(state))
  }
  let dispatch = function(action){
    // 用来触发reducer 
    console.log(action)
    state = reducer(state,action)
    console.log(1111,state)
    listeners.forEach(item=>{
      item&&item()
    })
  }
  dispatch({})// 是为了给 私有变量state一个初始值
  let subscribe = function(f){
    listeners.push(f)
    return ()=>{
      listeners = listeners.filter(item=>item!==f)
    }
  }
  if(typeof fn == 'function'){
    return fn(createStore)(reducer)
  }
  return {
    getState,
    dispatch,
    subscribe
  }
}
export function combineReducers(obj){
  //obj:{todo:todoReducer,color:colorReducer}
  return function (state={},action){
    Object.keys(obj).forEach(item=>{
      //obj[item]  todoReducer colorReducer
      state[item] = obj[item](state[item],action)
    })
    return state
  }
}


export const compose = (...fns)=>(...arg)=>{
  let first = fns.shift()
  return fns.reduce((prev,cur)=>{
    return cur(prev)
  },first(...arg))
}
export function applyMiddleware(...middleware){
  //middleware thunk
  return function (createStore){
    return function (reducer){
      let store = createStore(reducer)// {getState,dispatch,subscribe}
      // let middle = middleware(store)
      let middles = middleware.map(item=>item(store))
      console.log(111111,middles)
      // let temps = middles.map(item=>item(store.dispatch))
      // console.log(222222,temps)
      // let temp = middles[1](store.dispatch)
      // temp 是一个新的dispatch
      let temp = compose(...middles)(store.dispatch)
      return {
        ...store,
        dispatch:temp
      }
    }
  }

}







// export function applyMiddleware(middleware){
//   //middleware thunk
//   return function (createStore){
//     return function (reducer){
//       let store = createStore(reducer)// {getState,dispatch,subscribe}
//       let middle = middleware(store)
//       console.log(middleware,middle)
//       let temp = middle(store.dispatch)
//       // temp 是一个新的dispatch
//       return {
//         ...store,
//         dispatch:temp
//       }
//     }
//   }

// }


